package com.hsource.doctorcenter.controller;

import com.hsource.common.utils.CommonResp;
import com.hsource.common.utils.resultUtils.controller.BaseController;
import com.hsource.doctorcenter.service.file.IFileService;
import com.hsource.doctorcenter.util.RedisUtil;
import com.hsource.doctorcenter.util.enums.UrlEnum;
import javazoom.jl.decoder.Bitstream;
import javazoom.jl.decoder.BitstreamException;
import javazoom.jl.decoder.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yangYang
 * @version 1.0
 * @date 2020/9/27 10:31
 * @describe
 */
@Controller
@RequestMapping("/file")
public class FileController  extends BaseController {
    @Autowired
    private IFileService fileService;
    @Autowired
    private RedisUtil redisUtil;



    @RequestMapping("/showImage/{imageUrl}")
    public void showPhoto(@PathVariable("imageUrl")String imageUrl, HttpServletResponse response) {
        OutputStream outputStream = null;
        try {
            String imageBase64String = redisUtil.get("webStock-center:image:"+imageUrl).toString();
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] getData = decoder.decodeBuffer(imageBase64String);
            outputStream = response.getOutputStream();
            outputStream.write(getData);
            outputStream.flush();
        } catch (Exception e) {
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
            }
        }
    }



    /**
     * 文件上传
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/fileUpload")
    @ResponseBody
    public CommonResp fileUpload(MultipartHttpServletRequest request,String type) throws IOException, URISyntaxException, BitstreamException {
        Map<String, Object> objectMap = fileService.uploadOssFile(request);

        Map<String, String> map=new HashMap<>();
        if(objectMap.get("error").equals("0")) {
            if (objectMap.containsKey("files")) {
                List<String> files = (List<String>) objectMap.get("files");
                if (files.stream().count() > 0) {
                    String collect = files.stream().collect(Collectors.joining(","));
                    map.put("files", collect);
                    map.put("messageType", type);
                    if (type.equals("audio")) {
                        URL url = new URL(collect);
                        URLConnection con = null;
                        try {
                            con = url.openConnection();
                            BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
                            Bitstream bt = new Bitstream(bis);
                            //获取mp3时间长度
                            Header header = bt.readFrame();
                            int mp3Length = con.getContentLength();
                            int time = (int) header.total_ms(mp3Length)/1000;
                            map.put("duration", String.valueOf(time));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }


                    }
                }
            }
        }else{
            return failed(objectMap.get("error_msg").toString());
        }
        return success(map);
    }
}
